from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column
from sqlalchemy import VARCHAR, Integer, DATE


class BaseModel:
    """
    DB_USER:数据库用户名
    DB_PASSWORD:数据库用户密码
    DB_HOST:数据库连接地址
    """
    host = 'cdb-bp68zbzf.gz.tencentcdb.com'
    user = 'itquestion996icu'
    password = 'fuckyou996'
    database = 'goof_off'
    port = 10037

    # echo参数为False时,表示不打印sqlalchemy日志,True则打印 ( 建议设置为False关闭掉,不然会有非常多的日志信息 )
    engine = create_engine(f'mysql+pymysql://{user}:{password}@{host}:{port}/{database}?charset=utf8',
                           echo=False)

    base = declarative_base()


class BaseModelField:
    _id = Column(Integer, primary_key=True, autoincrement=True)
    no = Column(Integer, default=0)
    hour = Column(Integer, default=0)
    day = Column(Integer, default=0)
    fetched_at = Column(DATE)

    def __init__(self, **items):
        for key in items:
            if hasattr(self, key) and key != "id":
                setattr(self, key, items[key])


class MysqlHelpers:
    def __init__(self, model):
        self.session = sessionmaker(bind=BaseModel.engine)()
        self.model = model
        self.model.metadata.create_all(BaseModel.engine)

    def write(self, items):

        try:
            data = self.model(**items)
            self.session.add(data)
            self.session.commit()
        except():
            self.session.rollback()
        finally:
            self.session.close()
